// ==================== 收货地址管理页面 ====================

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/address.module.css";
import redIcon from "../img/red.png";
import deleteIcon from "../img/cha.png";
import whiteIcon from "../img/white.png";
import leftArrowIcon from "../img/left.png";
import { address, address_save, address_del } from "../api/address"; //收货地址接口

// 类型定义
interface AddressItem {
  id: number;
  name: string;
  tel: string;
  default: number; // 1表示默认地址，0表示非默认
  address: string;
}

const AddressPage = () => {
  // 状态管理
  const [addressList, setAddressList] = useState<AddressItem[]>([]);
  const [showSuccessHint, setShowSuccessHint] = useState(false);
  const navigate = useNavigate();
  
  // 从本地存储获取用户信息
  const user = JSON.parse(localStorage.getItem("user") || "null");
  const userId = user?.data?.id;
  const userToken = user?.data?.token;

  // 组件挂载时获取地址列表
  useEffect(() => {
    fetchAddressList();
  }, []);

  /**
   * 获取用户地址列表
   */
  const fetchAddressList = async () => {
    try {
      const response = await address({ uid: userId });
      setAddressList(response.data.data || []);
    } catch (error) {
      console.error("获取地址列表失败:", error);
    }
  };

  /**
   * 删除地址
   * @param id 地址ID
   */
  const handleDeleteAddress = async (id: number) => {
    try {
      await address_del({ id });
      setShowSuccessHint(true);
      setTimeout(() => setShowSuccessHint(false), 2000);
      fetchAddressList(); // 刷新地址列表
    } catch (error) {
      console.error("删除地址失败:", error);
    }
  };

  /**
   * 编辑地址
   * @param index 地址索引
   * @param id 地址ID
   */
  const handleEditAddress = (index: number, id: number) => {
    const selectedAddress = addressList[index];
    // 存储编辑所需数据到本地
    localStorage.setItem("editAddressId", id.toString());
    localStorage.setItem("editAddressData", JSON.stringify(selectedAddress));
    localStorage.setItem("allAddresses", JSON.stringify(addressList));
    navigate("/editaddress");
  };

  /**
   * 返回上一页
   */
  const handleGoBack = () => navigate(-1);

  /**
   * 跳转到新增地址页面
   */
  const handleAddNewAddress = () => navigate("/newadd");

  return (
    <div className={styles.container} style={{ backgroundColor: "#F4F4F4" }}>
      {/* 操作成功提示 */}
      {showSuccessHint && (
        <div className={styles.hintContainer}>
          <div className={styles.hint}>删除成功！</div>
        </div>
      )}

      {/* 顶部导航栏 */}
      <div className={styles.topBar}>
        <div className={styles.navContent}>
          <img 
            onClick={handleGoBack} 
            src={leftArrowIcon} 
            alt="返回" 
            className={styles.backIcon} 
          />
          <b className={styles.title}>收货地址</b>
        </div>
      </div>

      {/* 地址列表区域 */}
      <div className={styles.addressListWrapper}>
        <div style={{ height: "10px" }}></div>
        
        {addressList.map((address, index) => (
          <div key={address.id} className={styles.addressItem}>
            <div className={styles.addressInfo}>
              <span className={styles.userName}>{address.name}</span>
              <span className={styles.userPhone}>{address.tel}</span>
              {address.default === 1 && (
                <span className={styles.defaultTag}>默认</span>
              )}
              <p className={styles.fullAddress}>{address.address}</p>
            </div>
            
            <div className={styles.addressActions}>
              <img
                src={redIcon}
                alt="编辑"
                onClick={() => handleEditAddress(index, address.id)}
                className={styles.actionIcon}
              />
              <img
                src={deleteIcon}
                alt="删除"
                onClick={() => handleDeleteAddress(address.id)}
                className={styles.actionIcon}
              />
            </div>
          </div>
        ))}
      </div>

      {/* 底部新增地址按钮 */}
      <div 
        className={styles.addButton} 
        onClick={handleAddNewAddress}
      >
        <img src={whiteIcon} alt="新增" className={styles.addIcon} />
        <b>新增地址</b>
      </div>
    </div>
  );
};

export default AddressPage;